<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div >
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr >
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in message" :key="item.id">
          <td>{{item.id }}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      message: [
        {id: 1, uname: 'Tom', age: 19, sex:'男'},
        {id: 2, uname: '小李', age: 18, sex:'女'},
        {id: 3, uname: '小王', age: 20, sex:'男'},
      ],
      uname:'',
      age:'',
      sex:'',
      id:'',
      flag:true
    }
  },
  methods:{
    // 添加
    add(){
      if(this.uname && this.age && this.sex){
       
        if(this.flag === true){
          const obj = {
        id:this.message.length + 1,
        uname:this.uname,
        age:this.age,
        sex:this.sex
       }
       this.message.push(obj)
       this.uname = ''
       this.age = '' 
       this.sex=''  
        }else{
          this.message[this.flag].uname = this.uname
          this.message[this.flag].age = this.age
          this.message[this.flag].sex  = this.sex

          this.uname = ''
          this.age = '' 
          this.sex=''
          this.flag = true
        }
      }else{
         return alert('请输入完整信息')
      }
    },
      
    // 删除
    del(id){
      this.message = this.message.filter((item)=>{
        return item.id !== id
      })
    },
    // 编辑
    edit(id){
          this.flag= id
          this.uname = this.message[id].uname
          this.age = this.message[id].age
          this.sex = this.message[id].sex
    }
  }
}

</script>
